import re
import pandas as pd
import numpy as np
from datetime import datetime

class LogAnalyzer:
    def __init__(self):
        # 定义日志解析的正则表达式
        self.patterns = {
            'timestamp': r'\[(\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2})\]',
            'eb_n0': r'Eb/N0:\s*([\d.]+)\s*dB',
            'elevation': r'天线俯仰角:\s*([\d.]+)\s*度'
        }
    
    def parse_log_file(self, file_path):
        """解析日志文件"""
        data = {
            'timestamp': [],
            'eb_n0': [],
            'elevation': []
        }
        
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                for line in f:
                    # 解析时间戳
                    timestamp_match = re.search(self.patterns['timestamp'], line)
                    if timestamp_match:
                        timestamp = datetime.strptime(
                            timestamp_match.group(1),
                            '%Y-%m-%d %H:%M:%S'
                        )
                    else:
                        continue
                    
                    # 解析Eb/N0
                    eb_n0_match = re.search(self.patterns['eb_n0'], line)
                    eb_n0 = float(eb_n0_match.group(1)) if eb_n0_match else None
                    
                    # 解析天线俯仰角
                    elevation_match = re.search(self.patterns['elevation'], line)
                    elevation = float(elevation_match.group(1)) if elevation_match else None
                    
                    # 只有当至少有一个值存在时才添加数据
                    if eb_n0 is not None or elevation is not None:
                        data['timestamp'].append(timestamp)
                        data['eb_n0'].append(eb_n0)
                        data['elevation'].append(elevation)
        
        except Exception as e:
            raise Exception(f"解析日志文件失败: {str(e)}")
        
        return pd.DataFrame(data)
    
    def analyze_log_data(self, df):
        """分析日志数据"""
        analysis = {
            'summary': {},
            'statistics': {},
            'correlations': {}
        }
        
        # 基本统计信息
        for column in ['eb_n0', 'elevation']:
            if df[column].notna().any():
                analysis['statistics'][column] = {
                    'min': df[column].min(),
                    'max': df[column].max(),
                    'mean': df[column].mean(),
                    'std': df[column].std(),
                    'median': df[column].median()
                }
        
        # 时间范围
        analysis['summary']['time_range'] = {
            'start': df['timestamp'].min(),
            'end': df['timestamp'].max(),
            'duration': (df['timestamp'].max() - df['timestamp'].min()).total_seconds() / 3600  # 小时
        }
        
        # 数据点数量
        analysis['summary']['data_points'] = len(df)
        
        # 计算相关性
        if df['eb_n0'].notna().any() and df['elevation'].notna().any():
            correlation = df['eb_n0'].corr(df['elevation'])
            analysis['correlations']['eb_n0_vs_elevation'] = correlation
        
        return analysis
    
    def get_time_series_data(self, df, column):
        """获取时间序列数据"""
        if column not in df.columns or not df[column].notna().any():
            return None
            
        return {
            'timestamps': df['timestamp'].tolist(),
            'values': df[column].tolist()
        }
    
    def detect_anomalies(self, df, column, threshold=2):
        """检测异常值"""
        if column not in df.columns or not df[column].notna().any():
            return []
            
        mean = df[column].mean()
        std = df[column].std()
        
        anomalies = df[abs(df[column] - mean) > threshold * std]
        
        return [{
            'timestamp': row['timestamp'],
            'value': row[column],
            'deviation': abs(row[column] - mean) / std
        } for _, row in anomalies.iterrows()] 